import axios from 'axios';
import { ElMessage,ElMessageBox } from 'element-plus';
// 创建axios实例
const service = axios.create({
  baseURL: '/api', // 使用相对路径
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    if(config.data instanceof FormData){
      delete config.headers['Content-Type'];
    }
    // 获取请求的URL
    const url = config.url;

    // 如果是登录或注册请求，不需要添加token
    if (url === '/login' || url === '/register') {
      return config;
    }

    // 其他请求需要添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    } else {
      // 如果没有token，可以在这里处理未登录的情况
      ElMessageBox.confirm(
        '登录已过期，是否重新登录？',
        '提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
      })
    }
    return config;
  },
  error => {
    // 对请求错误做些什么
    ElMessage.error('请求错误:' + error)
    console.error('请求错误:', error);

    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    const res = response.data;
    if (res == 'Token验证未通过！') {
      ElMessageBox.confirm(
        '登录已过期，是否重新登录？',
        '提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        localStorage.removeItem('token')
        window.location.href = '/login'
      })
      return
    }else if(res == 'Token不存在！'){
      ElMessageBox.confirm(
        '登录已过期，是否重新登录？',
        '提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        localStorage.removeItem('token')
        window.location.href = '/login'
      })
      return
    }else if(res == '用户无权限！'){
      ElMessage.error('用户无权限！')
      return
    }
    return res;
  },
  error => {
    // 对响应错误做点什么
    ElMessage.error('响应错误:' + error)
    // ElMessageBox.confirm(
    //   '登录已过期，是否重新登录？',
    //   '提示',
    //   {
    //     confirmButtonText: '重新登录',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }
    // ).then(() => {
    //   localStorage.removeItem('token')
    //   window.location.href = '/login'
    // })
    console.error('响应错误:', error);
  
    return Promise.reject(error);
  }
);

// 封装GET请求
export function get(url, params) {
  return service({
    url,
    method: 'get',
    params,
  });
}

// 封装POST请求
export function post(url, data) {
  return service({
    url,
    method: 'post',
    data
  });
}

// 封装PUT请求
export function put(url, data) {
  return service({
    url,
    method: 'put',
    data,
  });
}

// 封装DELETE请求
export function del(url) {
  return service({
    url,
    method: 'delete',
  });
}

// 封装文件上传请求
export function uploadFile(url, file, onProgress) {
  const formData = new FormData();
  formData.append('file', file);
  
  return service({
    url,
    method: 'post',
    data: formData,
    onUploadProgress: (progressEvent) => {
      if (onProgress) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(percentCompleted);
      }
    }
  });
}

// 封装文件下载请求
export function downloadFile(url, filename, onProgress) {
  return service({
    url,
    method: 'get',
    responseType: 'blob',
    onDownloadProgress: (progressEvent) => {
      if (onProgress) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(percentCompleted);
      }
    }
  }).then(response => {
    const blob = new Blob([response]);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
}

export default service; 